package com.example.emos.wx.config.shiro;

import com.example.emos.wx.db.pojo.TbUser;
import com.example.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Author yctc
 * @Date 2021/3/6 15:10
 * @Version 1.0
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    /**
     * 让JavaWeb项目传入封装好的token对象,不是字符串
     * 作用: 判断传入的token对象是否符合要求
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        TbUser user = (TbUser) collection.getPrimaryPrincipal();//获得用户基本信息
        int id = user.getId();//获得用户主键值-> id
        Set<String> permissions = userService.searchUserPermissions(id);//根据ID查询用户权限列表
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//创建授权对象
        info.setStringPermissions(permissions);//把用户权限列表封装在授权对象中
        return info;
    }

    /**
     * 认证(登录时调用)
     * 返回认证对象
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String accessToken = (String) token.getPrincipal(); // AuthenticationToken 不是字符串类型的token-> 先获的字符串token
        int userId = jwtUtil.getUserId(accessToken);// 根据token获得userID
        TbUser user = userService.searchById(userId);// 查询用户信息

        /**
         *  员工已经离职 status=2 , 但是 token 并没过期
         */
        if (user == null) {
            throw new LockedAccountException("账号被锁定,请联系管理员");
        }

        // 颁发认证对象
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());// 向认证对象的构造器传入参数 -> user,token,getName()
        //TODO 往info对象中添加用户信息、Token字符串

        return info;
    }
}
